<?php

$nodb = false;
if ($local_dev) {
    $connection = mysql_connect('localhost', 'root', '');
    $dbname = "plastiz";
} else {
    $connection = mysql_connect('localhost', 'plastiz', 'hXG3GoaBUq5s77B');
    $dbname = "plastiz_";
}
mysql_select_db($dbname) or $nodb = true;
if ($nodb) {
    mysql_query("CREATE DATABASE IF NOT EXISTS " . $dbname, $connection);
    mysql_select_db($dbname, $connection) or die("Connection failed");
    mysql_query("CREATE TABLE link
    (
    id int NOT NULL AUTO_INCREMENT,
    PRIMARY KEY(id),
    link varchar(100),
    name varchar(100)
)", $connection);
    mysql_query("CREATE TABLE sublink
    (
    id int NOT NULL AUTO_INCREMENT,
    PRIMARY KEY(id),
    link_id int(7),
    link varchar(100),
    name varchar(100)
)", $connection);
}

mysql_query("SET NAMES 'utf8';");
mysql_query("SET CHARACTER SET 'utf8';");
mysql_query("SET SESSION collation_connection = 'utf8_general_ci';");

function my_mysql_error() {
    global $SMARTY, $S, $base;
    if (@mysql_error()) {
        $SMARTY->assign('ERROR', preg_replace("/(.+?to use near )(.+)/si", "\$1<span style=\"color:red\">\$2</span>", mysql_error()));
        $SMARTY->assign('L', $S->L);
        $SMARTY->display(APPROOT_PATH . 'templates/error.tpl');
        exit;
    }
}

function mysql_insert($table_name, $insert_fields, $do_not_addslashes = false) {
    $qstr = "INSERT INTO `" . $table_name . "` (`" .
            implode("`, `", array_keys($insert_fields)) . "`) VALUES ('" .
            implode("', '", ($do_not_addslashes ? array_values($insert_fields) : array_values($insert_fields))) . "')";
    mysql_query($qstr);
}

function mysql_insert_array($table_name, $insert_fields_array, $ignore = false) {
    $array_fst_element = array_first_element($insert_fields_array);
    if (is_array($array_fst_element)) {
        $qstr = "INSERT " . ($ignore ? "IGNORE" : "") . " INTO `" . $table_name . "` (`";
        $qstr .= implode("`, `", array_keys($array_fst_element)) . "`) VALUES ";
        $rows = array();
        foreach ($insert_fields_array as $insert_fields) {
            $rows[] = "('" . implode("', '", my_addslashes(array_values($insert_fields))) . "')";
        }
        if ($rows) {
            mysql_query($qstr . implode(",", $rows));
        }
    } else {
        return mysql_insert($table_name, $insert_fields_array);
    }
}

function mysql_insert_if_absent($table_name, $insert_fields, $check_fields) {
    $qstr = "SELECT `id` FROM `" . $table_name . "` WHERE 1=1 ";
    $condition = '';

    foreach ($check_fields as $field_name => $field_value) {
        $condition .= " AND `" . $field_name . "` = '" . my_addslashes($field_value) . "' ";
    }

    $qstr = $qstr . $condition;

    $query = mysql_query($qstr, DB_SERVER_FOR_SELECT_Q);
    $id = @mysql_result($query, 0);

    if ($id) {
        return $id;
    } else {
        return mysql_insert($table_name, $insert_fields);
    }
}

function mysql_insert_or_update($table_name, $insert_fields, $check_fields, $update_fields = "", $do_not_addslashes = false) {
    $qstr = "SELECT `id` FROM `" . $table_name . "` WHERE 1=1 ";
    $condition = '';
    foreach ($check_fields as $field_name => $field_value) {
        $condition .= " AND `" . $field_name . "` = '" . ($do_not_addslashes ? $field_value : my_addslashes($field_value)) . "' ";
    }
    $qstr = $qstr . $condition;

    $id = mysql_value($qstr);

    if ($id) {
        mysql_update($table_name, $update_fields ? $update_fields : $insert_fields, $id, $do_not_addslashes);
        return $id;
    } else {
        $id = mysql_insert($table_name, $insert_fields, $do_not_addslashes);
        return $id;
    }
}

function mysql_select_array() {
    $chache_options = null;
    $args = func_get_args();

    foreach ($args as $key => $value) {
        if (is_array($value)) {
            unset($args[$key]);
            $chache_options = $value;
            break;
        }
    }
    $qstr = array_shift($args);
    $result = array();
    $sql = sql_placeholder_ex($qstr, $args, $error);
    if (is_array($chache_options) && ($result = get_sql_cache($sql, $chache_options))) {
        return $result;
    }

    $query = mysql_query($sql);
    while ($row = mysql_fetch_assoc($query)) {
        $result[] = $row;
    }
    if (is_array($chache_options) && $result) {
        set_sql_cache($sql, $result, $chache_options);
    }
    return $result;
}

function mysql_value() {
    $chache_options = null;
    $args = func_get_args();
    $sql = array_shift($args);
    foreach ($args as $key => $value) {
        if (is_array($value)) {
            unset($args[$key]);
            $chache_options = $value;
            break;
        }
    }
    $result = array();
    $sql = sql_placeholder_ex($sql, $args, $error);
    if (is_array($chache_options) && ($ret_result = get_sql_cache($sql, $chache_options))) {
        return $ret_result;
    } elseif (is_array($chache_options)) {
        //if we use our cache - why should MySQL cache results?
        if (!strstr("SQL_NO_CACHE", $sql)) {
            $sql = preg_replace("#^SELECT #", "SELECT SQL_NO_CACHE ", $sql);
        }
    }

    if ($query = mysql_query($sql)) {
        while ($row = mysql_fetch_row($query)) {
            array_push($result, array_shift($row));
        }
    }

    if (count($result) == 0)
        $result = null;
    if (count($result) > 0)
        $result = $result[0];

    if (is_array($chache_options) && ($result != "")) {
        set_sql_cache($sql, $result, $chache_options);
    }
    return $result;
}

function mysql_row_assoc() {
    $chache_options = null;
    $args = func_get_args();
    $sql = array_shift($args);
    foreach ($args as $key => $value) {
        if (is_array($value)) {
            unset($args[$key]);
            $chache_options = $value;
            break;
        }
    }
    $sql = sql_placeholder_ex($sql, $args, $error);
    if (is_array($chache_options) && ($ret_result = get_sql_cache($sql, $chache_options))) {
        return $ret_result;
    }
    $result = array();

    $query = mysql_query($sql);
    $row = mysql_fetch_assoc($query);
    return $row;
}

function get_sql_cache($sql, $chache_options) {
    return getCache($chache_options['key_item'], array('hash_name' => $chache_options['hash_name'], "key_type" => $chache_options['key_type']), "Redis");
}

function set_sql_cache($sql, $values, $chache_options) {
    if ($chache_options['expire']) {
        setCache($chache_options['key_item'], $values, array('hash_name' => $chache_options['hash_name'], "key_type" => $chache_options['key_type'], 'expire' => $chache_options['expire']), "Redis");
    } else {
        setCache($chache_options['key_item'], $values, array('hash_name' => $chache_options['hash_name'], "key_type" => $chache_options['key_type']), "Redis");
    }
}

function mysql_update($table_name, $update_fields, $where, $do_not_addslashes = false, $where_selector_type = "AND") {
    $qstr = "UPDATE `" . $table_name . "` SET ";
    foreach ($update_fields as $key => $value) {
        $qstr .= "`" . $key . "` = '" . $value . "', ";
    }
    $qstr = preg_replace("#,$#si", '', trim($qstr));
    if (is_array($where)) {
        $qstr .= " WHERE 1=1 ";
        foreach ($where as $key => $value) {
            $qstr .= " " . $where_selector_type . " `" . $key . "` = '" . $value . "'";
        }
    } else {
        $qstr .= " WHERE `id` = '" . $where . "'";
    }
    mysql_query($qstr);
}

function mysql_row() {
    $args = func_get_args();
    $qstr = array_shift($args);

    $query = mysql_query(sql_placeholder_ex($qstr, my_addslashes($args), $error), DB_SERVER_FOR_SELECT_Q);
    $row = mysql_fetch_row($query);
    return $row;
}

function mysql_numrow() {
    $args = func_get_args();
    $qstr = array_shift($args);

    $query = mysql_query(sql_placeholder_ex($qstr, my_addslashes($args), $error), DB_SERVER_FOR_SELECT_Q);
    $row = mysql_num_rows($query);
    return $row;
}

function mysql_delete($table, $id, $where_selector_type = "AND", $key_name = "") {
    if (is_array($id)) {
        $where = array();
        foreach ($id as $key => $value) {
            $key = $key_name ? $key_name : $key;
            $where[] = " `" . $key . "` = '" . $value . "' ";
        }
        mysql_query("DELETE FROM " . $table . " WHERE " . implode($where_selector_type, $where));
    } else {
        mysql_query("DELETE FROM " . $table . " WHERE `id` = '" . $id . "'");
    }
}

function sql_pholder() {

    $args = func_get_args();
    $tmpl = array_shift($args);
    $result = sql_placeholder_ex($tmpl, $args, $error);
    if ($result === false) {
        $error = "Placeholder substitution error. Diagnostics: \"$error\"";
        if (function_exists("debug_backtrace")) {
            $bt = debug_backtrace();
            $error .= " in " . @$bt[0]['file'] . " on line " . @$bt[0]['line'];
        }
        trigger_error($error, E_USER_WARNING);
        return false;
    }
    return $result;
}

function sql_placeholder() {

    $args = func_get_args();
    $tmpl = array_shift($args);
    $result = sql_placeholder_ex($tmpl, $args, $error);
    if ($result === false)
        return PLACEHOLDER_ERROR_PREFIX . $error;
    else
        return $result;
}

function sql_compile_placeholder($tmpl) {

    $compiled = array();
    $p = 0;
    $i = 0;
    $has_named = false;

    while (false !== ($start = $p = strpos($tmpl, "?", $p))) {

        switch ($c = substr($tmpl, ++$p, 1)) {
            case '&':
            case '%':
            case '@':
            case '#':
                $type = $c;
                ++$p;
                break;
            default:
                $type = '';
                break;
        }

        if (preg_match('/^((?:[^\s[:punct:]]|_)+)/', substr($tmpl, $p), $pock)) {

            $key = $pock[1];
            if ($type != '#')
                $has_named = true;
            $p += strlen($key);
        } else {

            $key = $i;
            if ($type != '#')
                $i++;
        }

        $compiled[] = array($key, $type, $start, $p - $start);
    }

    return array($compiled, $tmpl, $has_named);
}

function sql_placeholder_ex($tmpl, $args, &$errormsg) {

    if (is_array($tmpl)) {
        $compiled = $tmpl;
    } else {
        $compiled = sql_compile_placeholder($tmpl);
    }

    list ($compiled, $tmpl, $has_named) = $compiled;

    if ($has_named)
        $args = @$args[0];

    $p = 0;
    $out = '';
    $error = false;

    foreach ($compiled as $num => $e) {

        list ($key, $type, $start, $length) = $e;

        $out .= substr($tmpl, $p, $start - $p);
        $p = $start + $length;

        $repl = '';
        $errmsg = '';

        do {

            if (!isset($args[$key]))
                $args[$key] = "";

            if ($type === '#') {
                $repl = @constant($key);
                if (NULL === $repl)
                    $error = $errmsg = "UNKNOWN_CONSTANT_$key";
                break;
            }

            if (!isset($args[$key])) {
                $error = $errmsg = "UNKNOWN_PLACEHOLDER_$key";
                break;
            }

            $a = $args[$key];
            if ($type === '&') {
                if ($a === "")
                    $repl = "null";
                else
                    $repl = "'" . addslashes($a) . "'";
                break;
            } else
            if ($type === '') {
                if (is_array($a)) {
                    $error = $errmsg = "NOT_A_SCALAR_PLACEHOLDER_$key";
                    break;
                }
                if ($a === "")
                    $repl = "null";
                else {
                    $repl = "'" . addslashes($a) . "'";
                }
                break;
            }

            if (!is_array($a)) {
                $error = $errmsg = "NOT_AN_ARRAY_PLACEHOLDER_$key";
                break;
            }

            if ($type === '@') {
                foreach ($a as $v) {
                    $repl .= ( $repl === '' ? "" : ",") . "'" . $v . "'";
                }
            } else
            if ($type === '%') {
                $lerror = array();
                foreach ($a as $k => $v) {
                    if (!is_string($k)) {
                        $lerror[$k] = "NOT_A_STRING_KEY_{$k}_FOR_PLACEHOLDER_$key";
                    } else {
                        $k = preg_replace('/[^a-zA-Z0-9_]/', '_', $k);
                    }
                    $repl .= ( $repl === '' ? "" : ", ") . $k . "='" . addslashes($v) . "'";
                }
                if (count($lerror)) {
                    $repl = '';
                    foreach ($a as $k => $v) {
                        if (isset($lerror[$k])) {
                            $repl .= ( $repl === '' ? "" : ", ") . $lerror[$k];
                        } else {
                            $k = preg_replace('/[^a-zA-Z0-9_-]/', '_', $k);
                            $repl .= ( $repl === '' ? "" : ", ") . $k . "=?";
                        }
                    }
                    $error = $errmsg = $repl;
                }
            }
        } while (false);

        if ($errmsg)
            $compiled[$num]['error'] = $errmsg;

        if (!$error)
            $out .= $repl;
    }
    $out .= substr($tmpl, $p);

    if ($error) {
        $out = '';
        $p = 0;
        foreach ($compiled as $num => $e) {
            list ($key, $type, $start, $length) = $e;
            $out .= substr($tmpl, $p, $start - $p);
            $p = $start + $length;
            if (isset($e['error'])) {
                $out .= $e['error'];
            } else {
                $out .= substr($tmpl, $start, $length);
            }
        }
        $out .= substr($tmpl, $p);
        $errormsg = $out;
        return false;
    } else {
        $errormsg = false;
        return $out;
    }
}

function placeholder() {

    $args = func_get_args();
    $tmpl = array_shift($args);

    $result = sql_placeholder_ex($tmpl, $args, $error);
    if ($result === false)
        return PLACEHOLDER_ERROR_PREFIX . $error;
    else
        return $result;
}

?>
